﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace idea.tools
{
    class HookTool
    {
          //定义委托（钩子函数,用于回调）
    public delegate int HookProc(int code, IntPtr wparam, ref CWPSTRUCT cwp);

    //安装钩子的函数
    [DllImport("User32.dll",CharSet = CharSet.Auto)]
    public static extern IntPtr SetWindowsHookEx(int type, HookProc hook, IntPtr instance, int threadID);
    //调用下一个钩子的函数
    [DllImport("User32.dll",CharSet = CharSet.Auto)]
    public static extern int CallNextHookEx(IntPtr hookHandle, int code, IntPtr wparam, ref CWPSTRUCT cwp);
    //卸载钩子
    [DllImport("User32.dll",CharSet = CharSet.Auto)]
    public static extern bool UnhookWindowsHookEx(IntPtr hookHandle);
    //获取窗体线程ID
    [DllImport("User32.dll",CharSet = CharSet.Auto)]
    public static extern int GetWindowThreadProcessId(IntPtr hwnd, int ID);

    private HookProc hookProc;
    private IntPtr hookHandle = IntPtr.Zero;

    public HookTool()
    {
      
        //挂接钩子处理方法
        this.hookProc = new HookProc(myhookproc);
    }

    //开始拦截
    private bool StartHook()
    {


//Form f = =new 
        //安装钩子，拦截系统向Form2发出的消息
    //  this.hookHandle = SetWindowsHookEx(4, hookProc, IntPtr.Zero ,GetWindowThreadProcessId(f.Handle,0));
    //   return (this.hookHandle !=(IntPtr) 0);
        return true;
    }


    //停止拦截
    private bool StopHook()
    {
        return UnhookWindowsHookEx(this.hookHandle);
    }

    //钩子处理函数，在这里拦截消息并做处理
    private int myhookproc(int code, IntPtr wparam, ref CWPSTRUCT cwp)
    {
        switch(code)
        {
        case 0:
        switch(cwp.message)
        {
            case 0x0000F://WM_PAINT，拦截WM_PAINT消息
                    //do something
            break;
        }
            break;
        }
        return CallNextHookEx(hookHandle,code,wparam, ref cwp);
    }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct CWPSTRUCT
    {
         public IntPtr lparam;
         public IntPtr wparam;
         public int message;
         public IntPtr hwnd;
    }

    }
}
